#coding:utf-8
from twisted.internet import defer
import os
import buss 
import dttime
import datamethod as dm
from protocols import *

def writeDataToFile(path, filename, data):
    if not os.path.exists(path): 
        os.mkdir(path)
    f = file("%s/%s"%(path, filename), 'wb')
    for d in data:
        f.write(d)
    f.close()
    
class Hunter(buss.BaseHunter):
    def init(self):
        self.imageData = {}
        self.photoNumbers = 0
        self.path = self.work.createSubPath("photos")
    
    def p_4101(self, data):
        p = Protocol4101(data)
        self.photoNumbers = (p.getCamera1() + p.getCamera2() + p.getCamera3()
                             + p.getCamera4()) * p.getNumbers()
        self.sendData(p)
        self.work.reportMessage(u"下发拍照指令4101.")
        
    def p_4141(self, data):
        p = Protocol4141(data)
        self.work.reportMessage(u"收到拍照应答4141.")
        if not p.getResponse():
            self.work.reportMessage(u"车辆拒绝拍照请求.")
            self.endWork()
        else:
            self.work.reportMessage(u"开始接收照片数据.")
            
    def p_4150(self, data):
        p = Protocol4150(data)
        curIndex = p.getImageIndex()
        curTotal = p.getPackageSum()
        curPackage = p.getPackageNumber()
        if not self.imageData.has_key(curIndex):
            self.imageData[curIndex] = dict([(i, None) for i in range(curTotal)])
        self.imageData[curIndex][curPackage] = p.getImageData()
        if p.needResponse():
            lack = self.checkImage(curIndex, curPackage)
            data = Protocol4110()
            data.setImageIndex(curIndex)
            data.setPackageNumber(curPackage)
            data.setLackPackage(lack)
            self.sendData(data)
            if not self.checkImage(curIndex, curTotal-1):
                self.savePhoto(curIndex)
                self.photoNumbers -= 1
                self.work.reportMessage(u"完成一张照片数据传输,剩余:%s."%self.photoNumbers)
            if self.photoNumbers <= 0:
                self.endWork()
                self.work.reportMessage(u"该拍照业务完成.")
                        
    def p_4152(self, data):
        p = Protocol4152(data)
        lack = []
        curPackage = p.getPackageNumber()
        curIndex = p.getImageIndex() 
        lack = self.checkImage(curIndex, curPackage)
        data = Protocol4112()
        data.setImageIndex(curIndex)
        data.setPackageNumber(curPackage)
        data.setLackPackage(lack)
        self.sendData(data)
    
    def savePhoto(self, photoIndex):
        filename = "%04x-%s.jpg"%(photoIndex, dttime.series())
        data = self.imageData[photoIndex]
        photo = []
        for i in range(len(data)):
            photo.append(dm.data2hex(data.get(i, [])))
            data[i] = None # clear
        defer.succeed(self.path).addCallback(writeDataToFile, filename, photo)
        #for i in data:data[i] = None

    def checkImage(self, curIndex, curPackage):
        lack = []
        if self.imageData.has_key(curIndex):
            for number in range(curPackage+1):
                if not self.imageData[curIndex][number]:
                    lack.append(number)
        else:
            lack = [i for i in range(curPackage+1)]
        return lack
            
            